package com.xianniu.ltc.service.impl;

import cn.devezhao.bizz.privileges.DepthEntry;
import cn.devezhao.bizz.privileges.Privileges;
import cn.devezhao.bizz.privileges.impl.BizzDepthEntry;
import cn.devezhao.bizz.privileges.impl.BizzPermission;
import cn.devezhao.bizz.security.member.BusinessUnit;
import cn.devezhao.bizz.security.member.Role;
import cn.devezhao.persist4j.Entity;
import cn.devezhao.persist4j.Field;
import cn.devezhao.persist4j.Record;
import cn.devezhao.persist4j.engine.ID;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONAware;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.JsonObject;
import com.rebuild.core.Application;
import com.rebuild.core.UserContextHolder;
import com.rebuild.core.configuration.general.ClassificationManager;
import com.rebuild.core.configuration.general.MultiSelectManager;
import com.rebuild.core.metadata.EntityHelper;
import com.rebuild.core.metadata.MetadataHelper;
import com.rebuild.core.privileges.UserHelper;
import com.rebuild.core.privileges.UserService;
import com.rebuild.core.privileges.bizz.Department;
import com.rebuild.core.privileges.bizz.User;
import com.rebuild.core.service.approval.ApprovalState;
import com.rebuild.core.service.general.series.SeriesGeneratorFactory;
import com.rebuild.utils.JSONUtils;
import com.xianniu.ltc.mapper.*;
import com.xianniu.ltc.model.entity.*;
import com.xianniu.ltc.model.po.report.ChartCommonPermissionsPO;
import com.xianniu.ltc.model.po.report.ReportLeadPO;
import com.xianniu.ltc.model.vo.CashTransferSchemesVO;
import com.xianniu.ltc.model.vo.statistics.StatisticsYVO;
import com.xianniu.ltc.model.vo.statistics.BenNianQianYueEVO;
import com.xianniu.ltc.model.vo.StatisticsXYVO;
import com.xianniu.ltc.model.vo.report.ReportLeadInfoVO;
import com.xianniu.ltc.model.vo.statistics.WebStatisticsXYVO;
import com.xianniu.ltc.service.ChaoNengBaoShangJiService;
import com.xianniu.ltc.service.CustomizedService;
import com.xianniu.ltc.service.NicheCodeService;
import com.xxl.sso.core.entity.ReturnT;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author WangRuiJie
 * @Title: CustomizedServiceImpl
 * @Package com.xianniu.ltc.service.impl
 * @Description: 定制化实现类
 * @date 2022/5/73:27 下午
 */
@Slf4j
@Service
public class CustomizedServiceImpl implements CustomizedService {

    @Resource
    private TCaiGouDingDanGuiJiMapper caiGouDingDanGuiJiMapper;
    @Resource
    private TCaiGouDingDanMingXiGuiJiMapper caiGouDingDanMingXiGuiJiMapper;
    @Resource
    private TDuiZhangDanMapper duiZhangDanMapper;
    @Resource
    private TDuiZhangDanMingXiMapper duiZhangDanMingXiMapper;
    @Resource
    private TXnLeadMapper leadMapper;
    @Resource
    private TTeshujiageshenpiMapper teshujiageshenpiMapper;
    @Resource
    private THuikuanjihuaMapper huikuanjihuaMapper;
    @Resource
    private TRbhetong0Mapper tRbhetong0Mapper;
    @Autowired
    private NicheCodeService nicheCodeService;
    @Autowired
    private ChaoNengBaoShangJiService chaoNengBaoShangJiService;

    /**
     * 校验勾选的采购订单是否存在已对账的数据
     * @return
     */
    @Override
    public boolean checkIsReconciliation(String[] ids) {
        List<TCaiGouDingDanGuiJiDTO> dtos = selectGuiJiList(ids);
        if (CollectionUtils.isNotEmpty(dtos)){
            for (TCaiGouDingDanGuiJiDTO dto : dtos) {
                // 存在对账为'是'的则直接返回
                if (dto.getDuizhangzhuangtai().equals("是")){
                    return false;
                }
            }
        }

        return true;
    }

    /**
     * 校验勾选的采购订单是否是统一供应商
     * @return
     */
    @Override
    public boolean checkIsSameSupplier(String[] ids) {
        Map<String, String> map = new HashMap<>();
        List<TCaiGouDingDanGuiJiDTO> dtos = selectGuiJiList(ids);
        if (CollectionUtils.isNotEmpty(dtos)){
            for (TCaiGouDingDanGuiJiDTO dto : dtos) {
                map.put(dto.getGongyingshangmingcheng(), dto.getGongyingshangmingcheng());
            }
            if (map.size() > 1){
                return false;
            }
        }
        return true;
    }

    /**
     * 采购单创建为对账单
     * @param ids
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, rollbackFor = Exception.class)
    @Override
    public ReturnT saveReconciliationOrder(String[] ids) {
        ID userId = UserContextHolder.getUser();
        User checkedUser = Application.getUserStore().getUser(userId);
        List<TCaiGouDingDanGuiJiDTO> dtos = selectGuiJiList(ids);
        BigDecimal sumJine = BigDecimal.ZERO;
        if (CollectionUtils.isNotEmpty(dtos)) {
            // 采购单所有的订单明细
            List<TCaiGouDingDanMingXiGuiJiDTO> detailList = new ArrayList<>();
            for (TCaiGouDingDanGuiJiDTO dto : dtos) {
                sumJine.add(dto.getDingdanjinehanshui()==null?BigDecimal.ZERO:dto.getDingdanjinehanshui());
                // 通过采购订单id查询采购订单明细
                QueryWrapper<TCaiGouDingDanMingXiGuiJiDTO> wrapper = new QueryWrapper();
                wrapper.eq("CAIGOUDINGDANGUIJI_ID", dto.getCaigoudingdanguijiId());
                List<TCaiGouDingDanMingXiGuiJiDTO> details = caiGouDingDanMingXiGuiJiMapper.selectList(wrapper);
                detailList.addAll(details);
            }
            // 开始保存对账单
            TDuiZhangDan3DTO dan3DTO = new TDuiZhangDan3DTO();
            ID id= ID.newId(EntityHelper.Rbduizhangdan3);
            // 确认对账单字段，保存对账单
            dan3DTO.setRbduizhangdan3Id(id.toString());
            dan3DTO.setDuizhangdanbianhao(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss")));
            String mingc = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))+dtos.get(0).getGongyingshangmingcheng()+"的对账单";
            // 对账单金额
            dan3DTO.setDuizhangdanjine(sumJine);
            // 供应商
            dan3DTO.setGongyingshangmingcheng(dtos.get(0).getGongyingshangmingcheng());
            dan3DTO.setDuizhangdanmingcheng(mingc);
            dan3DTO.setCaigoudingdan(String.join(",", ids));
            dan3DTO.setOwningUser(userId.toString());
            dan3DTO.setCreatedBy(userId.toString());
            dan3DTO.setModifiedBy(userId.toString());
            dan3DTO.setOwningDept(checkedUser.getOwningDept().getIdentity().toString());
            log.info("保存对账单数据：{}", JSON.toJSON(dan3DTO));
            duiZhangDanMapper.insert(dan3DTO);

            // 确认对账单明细字段，保存对账单明细
            if (CollectionUtils.isNotEmpty(detailList)){
                for (TCaiGouDingDanMingXiGuiJiDTO mingXiGuiJiDTO : detailList) {
                    TDuiZhangDanMingXiDTO mingXiDTO = new TDuiZhangDanMingXiDTO();
                    ID dId= ID.newId(EntityHelper.Duizhangdanmingxi);
                    BeanUtils.copyProperties(mingXiGuiJiDTO, mingXiDTO);
                    // 对账单明细ID
                    mingXiDTO.setDuizhangdanmingxiId(dId.toString());
                    // 对账单ID
                    mingXiDTO.setRbduizhangdan3Id(id.toString());
                    mingXiDTO.setCreatedBy(userId.toString());
                    mingXiDTO.setModifiedBy(userId.toString());
                    log.info("保存对账单明细数据：{}", JSON.toJSON(dan3DTO));
                    duiZhangDanMingXiMapper.insert(mingXiDTO);
                }
            }

            // 操作完成后修改采购单的对账状态为'是'
            for (TCaiGouDingDanGuiJiDTO dto : dtos) {
                log.info("操作完成后修改采购单:{}的对账状态为'是'", dto.getCaigoudingdanguijiId());
                TCaiGouDingDanGuiJiDTO newDto = new TCaiGouDingDanGuiJiDTO();
                newDto.setCaigoudingdanguijiId(dto.getCaigoudingdanguijiId());
                newDto.setDuizhangzhuangtai("是");
                caiGouDingDanGuiJiMapper.updateById(newDto);
            }
        }
        return new ReturnT();
    }


    /**
     * 对账单-完成对账单
     * @param ids
     * @return
     */
    @Override
    public ReturnT completeStatements(String[] ids) {
        ID userId = UserContextHolder.getUser();
        User checkedUser = Application.getUserStore().getUser(userId);
        for (String id : ids) {
            TDuiZhangDan3DTO dan3DTO = new TDuiZhangDan3DTO();
            dan3DTO.setRbduizhangdan3Id(id);
            dan3DTO.setDuizhangzhuangtai("T");
            dan3DTO.setRbduizhangren0(checkedUser.getFullName());
            dan3DTO.setWanchengshijian(LocalDateTime.now());
            dan3DTO.setModifiedBy(userId.toString());
            duiZhangDanMapper.updateById(dan3DTO);
        }
        return new ReturnT();
    }

    /**
     * 通过采购单ID查询采购单信息
     * @param ids
     * @return
     */
    private List<TCaiGouDingDanGuiJiDTO> selectGuiJiList(String[] ids){
        Map<String, String> map = new HashMap<>();
        List<String> idList = Arrays.asList(ids);
        QueryWrapper<TCaiGouDingDanGuiJiDTO> wrapper =new QueryWrapper<>();
        wrapper.in("CAIGOUDINGDANGUIJI_ID", idList);
        return caiGouDingDanGuiJiMapper.selectList(wrapper);
    }

    /**
     * 对账单完成后，不能修改
     * @param data
     */
    @Override
    public boolean doStatements(Record data){
        ID id = data.getPrimary();
        // id不为空则问修改
        if (id != null){
            TDuiZhangDan3DTO dan3DTO = duiZhangDanMapper.selectById(id.toString());
            if (dan3DTO != null){
                // 对账状态是 'T',完成状态
                if (dan3DTO.getDuizhangzhuangtai().equals("T")){
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 服务请求，报价金额大于商机金额判断
     *  报价金额>商机金额 && 对应商机生成了特殊价格审批 && 特殊价格审批为通过 则为true
     * @param data
     * @return
     */
    @Override
    public boolean doCheckMoneyForServiceRequest(Record data) {
        // 关联商机
        ID richI = data.getID("guanlianshangji");
        QueryWrapper<TTeshujiageshenpiDTO> wrapper = new QueryWrapper();
        wrapper.eq("GUANLIANSHANGJI", String.valueOf(richI));
        wrapper.eq("TENANT_CODE", UserContextHolder.getTenant());
        // 通过
        wrapper.eq("APPROVAL_STATE", ApprovalState.APPROVED.getState());
        List<TTeshujiageshenpiDTO> dataList=teshujiageshenpiMapper.selectList(wrapper);
        if (CollectionUtils.isEmpty(dataList)){
            return true;
        }
        return false;
    }

    /************************** 定制化报表列表相关 *****************************/

    /**
     * 功能描述: 定制化报表列表
     *
     * @Param: [entity, request]
     * @Return: com.alibaba.fastjson.JSONAware
     * @Author: wrj
     * @Date: 2022/5/18 11:14 上午
     */
    @Override
    public JSONAware reportDataList(String entity, ReportLeadPO po) {
        // 返回列表,以及总数
        switch (entity){
            case "lead":

                log.info("查询线索报表数据{}", JSON.toJSON(po));
                return reportLeadDataList(po);

                // 后续可能用很多报表
            case "shangJiNewAdd":

                log.info("查询商机新增数量 == {}", JSON.toJSON(po));
                return shangJiNewAddStatistics(po);

            case "shangJiNewIndustry":

                log.info("查询商机新增数量 按行业分布 == {}", JSON.toJSON(po));
                return shangJiNewAddIndustryStatistics(po);

            case "shangJiChaoNengBaoNewAdd":

                po.setType("2");
                log.info("查询超能保商机新增数量 == {}", JSON.toJSON(po));
                // 商机合并后 , 超能保商机不在继续单独保存一个表 , 而是通过商机类型进行区分
                // return shangJiChaoNengBaoNewAddStatistics(po);
                return shangJiNewAddStatistics(po);

            default:
                log.info("默认返回{}", JSON.toJSON(po));
                return new JSONObject();
        }
    }

    /**
     * lead
     * 查询线索报表数据
     * @param po
     * @return
     */
    private JSONObject reportLeadDataList(ReportLeadPO po){
        String tenantCode = UserContextHolder.getTenant();
        po.setTenantCode(tenantCode);
        List<ReportLeadInfoVO> vos = new ArrayList<>();
        // 查询当前用户对私海线索的权限
        JSONObject privateSea = selectPrivilegeByCurrentUser(EntityHelper.SiHaiXianSuo);
        // 查询当前用户对公海线索的权限
        JSONObject highSea = selectPrivilegeByCurrentUser(EntityHelper.GongHaiXianSuo);
        // 汇总当前用户对公私海线索有查询权限的,本人权限，部门权限集合
        if (privateSea.getString("owningUser") != null){
            po.setPOwningUser(privateSea.getString("owningUser"));
        }
        if (privateSea.getJSONArray("owningDept") != null) {
            po.setPOwningDept(privateSea.getJSONArray("owningDept").toJavaList(String.class));
        }
        if (highSea.getString("owningUser") != null){
            po.setHOwningUser(highSea.getString("owningUser"));
        }
        if (highSea.getJSONArray("owningDept") != null){
            po.setHOwningDept(highSea.getJSONArray("owningDept").toJavaList(String.class));
        }
        Page<TXnLeadDTO> page = new Page<>(po.getPageNum(), po.getPageSize());
        IPage<ReportLeadInfoVO> dtoList = leadMapper.selectReportPageList(page, po);
        // 数据为空，则处理数据返回
        if (CollectionUtils.isEmpty(dtoList.getRecords())){
            return JSONUtils.toJSONObject(
                    new String[]{"total", "data"},
                    new Object[]{0, vos});
        }
        // 循环重新组装数据
        for (ReportLeadInfoVO leadInfoVO : dtoList.getRecords()) {
            // 创建时间拆分为年，月，日，时段
            Integer nian = Integer.valueOf(leadInfoVO.getCreatedOn().substring(0, 4));
            Integer yue = Integer.valueOf(leadInfoVO.getCreatedOn().substring(5, 7));;
            Integer ri = Integer.valueOf(leadInfoVO.getCreatedOn().substring(8, 10));;
            String shiduan = leadInfoVO.getCreatedOn().substring(11);
            leadInfoVO.setNian(nian);
            leadInfoVO.setYue(yue);
            leadInfoVO.setRi(ri);
            leadInfoVO.setShiduan(shiduan);
            // 行业
            if (StringUtils.isNotBlank(leadInfoVO.getIndustry())){
                ID industry = ID.valueOf(leadInfoVO.getIndustry());
                String itemV = ClassificationManager.instance.getName(industry);
                leadInfoVO.setIndustry(itemV);
            }
            if (StringUtils.isNotBlank(leadInfoVO.getRbshangji4Id())){
                // 售前人员是私海线索对应的商机的售前协同的的下一步审批人
                List<String> nextApprovalUser = leadMapper.selectNextApprovalUserByNicheId(leadInfoVO.getRbshangji4Id());
                leadInfoVO.setShouqianren(String.join(",", nextApprovalUser));
            }
            if (StringUtils.isNotBlank(leadInfoVO.getYewuleixing())){
                Entity mainEntity = MetadataHelper.getEntity(EntityHelper.NicheCode);
                Field field = mainEntity.getField("yewuleixing");
                String[] valueLabels = MultiSelectManager.instance.getLabels(Long.valueOf(leadInfoVO.getYewuleixing()), field);
                leadInfoVO.setYewuleixing(Arrays.toString(valueLabels));
            }
        }
        log.info("线索报表数据返回日志-------->{}:", JSON.toJSON(dtoList.getRecords()));
        return JSONUtils.toJSONObject(
                new String[]{"total", "data"},
                new Object[]{dtoList.getTotal(), dtoList.getRecords()});
    }

    /**
     * 通过当前用户查询对应实体的权限
     * @param entityCode
     * @return
     */
    @Override
    public JSONObject selectPrivilegeByCurrentUser(int entityCode){
        JSONObject result = new JSONObject();
        ID userId = UserContextHolder.getUser();
        if (UserHelper.isAdmin(userId)) return result;
        User user = Application.getUserStore().getUser(userId);
        Role role = user.getOwningRole();
        Privileges ep = role.getPrivileges(entityCode);
        // 查询当前人对该实体读取的权限
        DepthEntry de = ep.superlative(BizzPermission.READ);
        // 当前用户所在部门
        Department dept = UserHelper.getDepartment(userId);
        // 坐在部门的所有子部门
        Set<BusinessUnit> units = dept.getAllChildrenModified();
        units.add(dept);
        // 无权限
        if(BizzDepthEntry.NONE.equals(de)){
            result.put("isNone", "T");
            // 本人
        }if(BizzDepthEntry.PRIVATE.equals(de)){
            result.put("owningUser", userId.toString());
        // 本部门
        }else if(BizzDepthEntry.LOCAL.equals(de)){
            result.put("owningDept", Arrays.asList(dept.getIdentity().toString()));
        // 管理员角色||权限是全公司
        }else if(userId.equals(UserService.ADMIN_USER)  || BizzDepthEntry.GLOBAL.equals(de)){

        // 本部门以及子部门
        }else if(BizzDepthEntry.DEEPDOWN.equals(de)){
            result.put("owningDept", units.stream().map(unit -> unit.getIdentity().toString()).collect(Collectors.toList()));
        }else{
            log.error("该用户在实体{}配置了错误的权限{}", entityCode, de);
        }
        log.info("当前用户对实体{}的读取权限的返回信息：{}", entityCode, result);
        return result;
    }

    /**
     * 本年回款统计：按周查询计划回款，按时收款，逾期收款数据
     * @return
     */
    @Override
    public StatisticsXYVO selectWeekCashTransferSchemesData( ChartCommonPermissionsPO po ){
        // 查询今天属于本年第几周
        Calendar c = Calendar.getInstance();
        // 设置每周的开始日期
        c.setFirstDayOfWeek(Calendar.MONDAY);
        c.setTime(new Date());
        c.setMinimalDaysInFirstWeek(7);
        // 当前周
        int week = c.get(Calendar.WEEK_OF_YEAR);
        Map<String, String> weekNameMap = new HashMap<String, String>();
        int[] weekList = new int[5];
        for ( int i=0; i<=4; i++ ){
            Integer tWeek = week-i;
            weekList[i] = tWeek;
            if( i==0 ){
                weekNameMap.put(tWeek.toString(), "本周");
            }else if(i>0){
                weekNameMap.put(tWeek.toString(), "前"+i+"周");
            }
        }
        log.info("这是周的查询条件的集合=={}", weekList);
        log.info("这是周的查询条件的名称集合=={}", weekNameMap);

        // 组装当前登录人对本年签约额的权限
        buildPermissionsForPo(po, EntityHelper.RbHeTong0);
        // 计划回款金额
        List<CashTransferSchemesVO> planData = huikuanjihuaMapper.selectWeekPlanData(po, weekList);
        // 按时回款
        List<CashTransferSchemesVO> onTimeData = huikuanjihuaMapper.selectWeekOnTimeData(po, weekList);
        // 逾期收回
        List<CashTransferSchemesVO> overdueData = huikuanjihuaMapper.selectWeekOverdueData(po, weekList);

        // 组装数据
        List<String> yWeekData = new ArrayList<String>();
        Map<Integer, Map<String, String>> WeekData = new HashMap<Integer, Map<String, String>>();
        List<Map<String, String>> xWeekData = new ArrayList<Map<String, String>>();
        for( int i=0; i<weekList.length; i++ ){
            Integer weekNum = weekList[i];
            String planWeekValue = "0";
            for (CashTransferSchemesVO plan:planData) {
                Integer planRiQi = plan.getRiqi();
                if( planRiQi==weekNum ){
                    planWeekValue = plan.getJine().toString();
                }
            }
            String onTimeWeekValue = "0";
            for (CashTransferSchemesVO onTime:onTimeData) {
                Integer onTimeRiQi = onTime.getRiqi();
                if( onTimeRiQi==weekNum ){
                    onTimeWeekValue = onTime.getJine().toString();
                }
            }

            String overdueWeekValue = "0";
            for (CashTransferSchemesVO overdue:overdueData) {
                Integer overdueRiQi = overdue.getRiqi();
                if( overdueRiQi==weekNum ){
                    overdueWeekValue = overdue.getJine().toString();
                }
            }

            Map<String, String> monthHuiKuanMap = new HashMap<String, String>();
            monthHuiKuanMap.put("plan",planWeekValue);
            monthHuiKuanMap.put("onTime",onTimeWeekValue);
            monthHuiKuanMap.put("overdue",overdueWeekValue);

            xWeekData.add(monthHuiKuanMap);
            yWeekData.add(weekNameMap.get(weekNum.toString()));
        }

        // 设置Y轴数据
        StatisticsYVO monthYVo = new StatisticsYVO();
        monthYVo.setData( yWeekData );
        monthYVo.setName( "本年回款统计" );
        // 周统计数据
        StatisticsXYVO monthXYVo = new StatisticsXYVO();
        monthXYVo.setXAxis(xWeekData);
        monthXYVo.setYyyAxis(monthYVo);
        return monthXYVo;
    }

    /**
     * 本年回款统计：按月查询计划回款，按时收款，逾期收款数据
     * @return
     */
    @Override
    public Map<String, StatisticsXYVO> selectMonthCashTransferSchemesData(ChartCommonPermissionsPO po) {
        // 组装当前登录人对回款计划的的操作权限
        buildPermissionsForPo(po, EntityHelper.Huikuanjihua);
        // 计划回款金额
        List<CashTransferSchemesVO> planData = huikuanjihuaMapper.selectMonthPlanData(po);
        // 按时回款
        List<CashTransferSchemesVO> onTimeData = huikuanjihuaMapper.selectMonthOnTimeData(po);
        // 逾期收回
        List<CashTransferSchemesVO> overdueData = huikuanjihuaMapper.selectMonthOverdueData(po);
        log.info("本年回款统计-月-计划=={}", planData);
        log.info("本年回款统计-月-按时=={}", onTimeData);
        log.info("本年回款统计-月-逾期=={}", overdueData);
        /* -------------------------------------------------------------------------------
         *  统计月 Start
         * --------------------------------------------------------------------------------------------------------------
         */
        List<String> yMonthData = new ArrayList<String>();
        Map<Integer, Map<String, String>> monthData = new HashMap<Integer, Map<String, String>>();
        List<Map<String, String>> xMonthData = new ArrayList<Map<String, String>>();
        for ( int i=1; i<=12; i++ ){
            String planMonthValue = "0";
            for (CashTransferSchemesVO plan:planData) {
                Integer riQi = plan.getRiqi();
                if( riQi==i ){
                    planMonthValue = plan.getJine().toString();
                }
            }
            String onTimeMonthValue = "0";
            for (CashTransferSchemesVO onTime:onTimeData) {
                Integer riQi = onTime.getRiqi();
                if( riQi==i ){
                    onTimeMonthValue = onTime.getJine().toString();
                }
            }

            String overdueMonthValue = "0";
            for (CashTransferSchemesVO overdue:overdueData) {
                Integer riQi = overdue.getRiqi();
                if( riQi==i ){
                    overdueMonthValue = overdue.getJine().toString();
                }
            }
            Map<String, String> monthHuiKuanMap = new HashMap<String, String>();
            monthHuiKuanMap.put("plan",planMonthValue);
            monthHuiKuanMap.put("onTime",onTimeMonthValue);
            monthHuiKuanMap.put("overdue",overdueMonthValue);
            monthData.put(i, monthHuiKuanMap);
            xMonthData.add(monthHuiKuanMap);
            yMonthData.add(i+"月");
        }
        // 设置Y轴数据
        StatisticsYVO monthYVo = new StatisticsYVO();
        monthYVo.setData( yMonthData );
        monthYVo.setName( "本年回款统计" );
        // 月统计数据
        StatisticsXYVO monthXYVo = new StatisticsXYVO();
        monthXYVo.setXAxis(xMonthData);
        monthXYVo.setYyyAxis(monthYVo);

        /* -------------------------------------------------------------------------------------
         *  统计月 End
         * ---------------------------------------------------------------------------------------------------------------
         */

        /* -------------------------------------------------------------------------------
         *  统计季 Start
         * --------------------------------------------------------------------------------------------------------------
         */
        StatisticsXYVO quarterXYVo = queryNowYearHuiKuanQuarter( monthData );
        /* -------------------------------------------------------------------------------------
         *  统计季 End
         * ---------------------------------------------------------------------------------------------------------------
         */
        Map<String, StatisticsXYVO> monthAndQuarterData = new HashMap<String, StatisticsXYVO>();
        monthAndQuarterData.put("month", monthXYVo);
        monthAndQuarterData.put("quarter", quarterXYVo);

        return monthAndQuarterData;
    }

    /**
     * 本年回款统计：按季度查询计划回款，按时收款，逾期收款数据
     * @return
     */
    @Override
    public JSONObject selectQuarterCashTransferSchemesData(ChartCommonPermissionsPO po) {
        // 组装当前登录人对回款计划的的操作权限
        buildPermissionsForPo(po, EntityHelper.Huikuanjihua);
        // 计划回款金额
        List<CashTransferSchemesVO> planData = huikuanjihuaMapper.selectQuarterPlanData(po);
        // 按时回款
        List<CashTransferSchemesVO> onTimeData = huikuanjihuaMapper.selectQuarterOnTimeData(po);
        // 逾期收回
        List<CashTransferSchemesVO> overdueData = huikuanjihuaMapper.selectQuarterOverdueData(po);
        return null;
    }

    /**
     * 组装当前登录人对实体的的操作权限
     * @param po
     * @return
     */
    public ChartCommonPermissionsPO buildPermissionsForPo (ChartCommonPermissionsPO po, int entityCode){
        String tenantCode = UserContextHolder.getTenant();
        po.setTenantCode(tenantCode);
        List<ReportLeadInfoVO> vos = new ArrayList<>();
        // 查询当前用户对公海线索的权限
        JSONObject hkjh = selectPrivilegeByCurrentUser(entityCode);
        // 汇总当前用户对实体有查询权限的,无权限，本人权限，部门权限集合
        if (hkjh.getString("isNone") != null){
            po.setIsNone(hkjh.getString("isNone"));
        }
        if (hkjh.getString("owningUser") != null){
            po.setPOwningUser(hkjh.getString("owningUser"));
        }
        if (hkjh.getJSONArray("owningDept") != null) {
            po.setPOwningDept(hkjh.getJSONArray("owningDept").toJavaList(String.class));
        }
        return po;
    }

    /**
     * 统计-本年-各地域-签约额
     * @return
     */
    @Override
    public StatisticsXYVO queryNowYearCityTop(ChartCommonPermissionsPO po ){
        log.info("进入top10===impl");
        // 组装当前登录人对本年签约额的权限
        buildPermissionsForPo(po, EntityHelper.RbHeTong0);

        // 数据插叙的统计数据
        List<BenNianQianYueEVO> trsxList = tRbhetong0Mapper.queryNowYearCityTop(po);

        // 地域名称作为Y轴data集合
        List<String> yData = new ArrayList<String>();
        List<String> xData = new ArrayList<String>();
        for (BenNianQianYueEVO item:trsxList) {
            yData.add(item.getName());
            xData.add(item.getValue().toString());
        }

        // 设置Y轴数据
        StatisticsYVO trsyVo = new StatisticsYVO();
        trsyVo.setData( yData );
        trsyVo.setName( "本年签约额top 10" );

        // 设置整个图标XY轴数据
        StatisticsXYVO trsVo = new StatisticsXYVO();
        trsVo.setXAxis(xData);
        trsVo.setYyyAxis(trsyVo);
        return trsVo;
    }

    /**
     * 统计-本年-各客户-签约额
     * @return
     */
    @Override
    public StatisticsXYVO queryNowYearKeHuTop(ChartCommonPermissionsPO po ){
        log.info("进入top10===impl");
        // 组装当前登录人对本年签约额的权限
        buildPermissionsForPo(po, EntityHelper.RbHeTong0);

        // 数据插叙的统计数据
        List<BenNianQianYueEVO> trsxList = tRbhetong0Mapper.queryNowYearKeHuTop(po);

        // 地域名称作为Y轴data集合
        List<String> yData = new ArrayList<String>();
        List<String> xData = new ArrayList<String>();
        for (BenNianQianYueEVO item:trsxList) {
            yData.add(item.getName());
            xData.add(item.getValue().toString());
        }

        // 设置Y轴数据
        StatisticsYVO trsyVo = new StatisticsYVO();
        trsyVo.setData( yData );
        trsyVo.setName( "本年签约额top 10" );

        // 设置整个图标XY轴数据
        StatisticsXYVO trsVo = new StatisticsXYVO();
        trsVo.setXAxis(xData);
        trsVo.setYyyAxis(trsyVo);
        return trsVo;
    }

    /**
     * 统计-本年-各销售部门-签约额
     * @return
     */
    @Override
    public StatisticsXYVO queryNowYearXiaoShouBuMen(ChartCommonPermissionsPO po ){
        log.info("进入销售部门===impl");
        // 组装当前登录人对本年签约额的权限
        buildPermissionsForPo(po, EntityHelper.RbHeTong0);
        // '上海业务部', '华中业务部', '区域销售-北京业务部', '广州业务部', '深圳业务部', '创新发展部', '电销业务部', '互联网业务部', '原厂业务部'
        Map<String, String> departmentNameMap = new HashMap<String, String>();
        departmentNameMap.put("上海业务部", "上海（区域）");
        departmentNameMap.put("深圳业务部", "深圳（区域）");
        departmentNameMap.put("区域销售-北京业务部", "北京（区域）");
        departmentNameMap.put("华中业务部", "华中（区域）");
        departmentNameMap.put("广州业务部", "广州（区域）");
        departmentNameMap.put("创新发展部", "创新发展");
        departmentNameMap.put("电销业务部", "电销");
        departmentNameMap.put("互联网业务部", "互联网");
        departmentNameMap.put("原厂业务部", "原厂");
        //departmentNameMap.put("总经办", "总经办部门");
        List<String> departmentNameList = new ArrayList<String>();
        for ( String nameKey:departmentNameMap.keySet() ){
            departmentNameList.add(nameKey);
        }
        log.info("部门条件=={}", departmentNameList );
        // 数据插叙的统计数据
        List<BenNianQianYueEVO> trsxList = tRbhetong0Mapper.queryNowYearXiaoShouBuMen(po, departmentNameList);

        // 查询业务拓展部包含：场外销售-业务拓展部、业务拓展-郑州分公司、业务拓展-烟台分公司、业务拓展-太原分公司、业务拓展-北京公司、业务拓展-成都分公司，相关部门统一为：业务拓展部；
        List<String> departmentName2List = new ArrayList<String>();
        departmentName2List.add("场外销售-业务拓展部");
        departmentName2List.add("业务拓展-郑州分公司");
        departmentName2List.add("业务拓展-烟台分公司");
        departmentName2List.add("业务拓展-太原分公司");
        departmentName2List.add("业务拓展-北京公司");
        departmentName2List.add("业务拓展-成都分公司");
        departmentName2List.add("业务拓展部");
        List<BenNianQianYueEVO> trsx2List = tRbhetong0Mapper.queryNowYearXiaoShouBuMen(po, departmentName2List);
        BigDecimal yeWuTuoZhanValue = BigDecimal.ZERO;
        if( trsx2List.size()>0 ){
            for (BenNianQianYueEVO item2:trsx2List) {
                yeWuTuoZhanValue = yeWuTuoZhanValue.add( item2.getValue() );
            }
            BenNianQianYueEVO bnqyEVo2 = new BenNianQianYueEVO();
            bnqyEVo2.setName("业务拓展部");
            bnqyEVo2.setValue(yeWuTuoZhanValue);
            trsxList.add(bnqyEVo2);
        }

        // 排序
        Collections.sort(trsxList, new Comparator<BenNianQianYueEVO>(){
            @Override
            public int compare(BenNianQianYueEVO b1, BenNianQianYueEVO b2) {
                return b2.getValue().compareTo(b1.getValue());
            }
        });

        // 地域名称作为Y轴data集合
        List<String> yData = new ArrayList<String>();
        List<String> xData = new ArrayList<String>();
        if( trsxList.size()>0 ){
            for (BenNianQianYueEVO item:trsxList) {
                if( item.getName().equals("业务拓展部") ){
                    yData.add("业务拓展部");
                }else{
                    yData.add(departmentNameMap.get(item.getName()));
                }
                xData.add(item.getValue().toString());
            }
        }

        // 设置Y轴数据
        StatisticsYVO trsyVo = new StatisticsYVO();
        trsyVo.setData( yData );
        trsyVo.setName( "本年销售部门签约额统计" );

        // 设置整个图标XY轴数据
        StatisticsXYVO trsVo = new StatisticsXYVO();
        trsVo.setXAxis(xData);
        trsVo.setYyyAxis(trsyVo);
        if( xData.size()<=0 ){
            Short isShow = 0;
            trsVo.setIsShow( isShow );
        }
        return trsVo;
    }

    /**
     * 统计-本年-周-签约额
     * @return
     */
    @Override
    public StatisticsXYVO queryNowYearWeek(ChartCommonPermissionsPO po ){
        // 查询今天属于本年第几周
        Calendar c = Calendar.getInstance();
        // 设置每周的开始日期
        c.setFirstDayOfWeek(Calendar.MONDAY);
        c.setTime(new Date());
        c.setMinimalDaysInFirstWeek(7);
        // 当前周
        int week = c.get(Calendar.WEEK_OF_YEAR);
        Map<String, String> weekNameMap = new HashMap<String, String>();
        int[] weekList = new int[5];
        for ( int i=0; i<=4; i++ ){
            Integer tWeek = week-i;
            weekList[i] = tWeek;
            if( i==0 ){
                weekNameMap.put(tWeek.toString(), "本周");
            }else if(i>0){
                weekNameMap.put(tWeek.toString(), "前"+i+"周");
            }
        }
        log.info("这是周的查询条件的集合=={}", weekList);
        log.info("这是周的查询条件的名称集合=={}", weekNameMap);

        // 组装当前登录人对本年签约额的权限
        buildPermissionsForPo(po, EntityHelper.RbHeTong0);

        // 数据插叙的统计数据
        List<BenNianQianYueEVO> trsxList = tRbhetong0Mapper.queryNowYearWeek(po, weekList);

        // 地域名称作为Y轴data集合
        List<String> yData = new ArrayList<String>();
        List<String> xData = new ArrayList<String>();

        for( int i=0; i<weekList.length; i++ ){
            String weekValue = "0";
            Integer weekNum = weekList[i];

            for (BenNianQianYueEVO item:trsxList) {
                String weekName = item.getName();
                if( weekNum.toString().equals(weekName) ){
                    weekValue = item.getValue().toString();
                }
            }
            xData.add(weekNameMap.get(weekNum.toString()));
            yData.add(weekValue);
        }

        // 设置Y轴数据
        StatisticsYVO trsyVo = new StatisticsYVO();
        trsyVo.setData( yData );
        trsyVo.setName( "本年销售部门签约额统计" );

        // 设置整个图标XY轴数据
        StatisticsXYVO trsVo = new StatisticsXYVO();
        trsVo.setXAxis(xData);
        trsVo.setYyyAxis(trsyVo);
        return trsVo;
    }

    /**
     * 历史累计应收未收款统计
     * @param po
     * @return
     */
    @Override
    public StatisticsXYVO queryHistoryWeiShouKuan(ChartCommonPermissionsPO po ){
        // 查询今天起 90天  90-180天  大于180天
        // 当前时间
        Calendar c = Calendar.getInstance();

        // 当前时间
        String now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(c.getTime());
        // 90天
        c.setTime(new Date());
        c.add(c.DAY_OF_YEAR, -89);
        String endTime90 = new SimpleDateFormat("yyyy-MM-dd").format( c.getTime() )+" 00:00:00";
        // 180天
        c.setTime(new Date());
        c.add(c.DAY_OF_YEAR, -179);
        String endTime180 = new SimpleDateFormat("yyyy-MM-dd").format( c.getTime() )+" 00:00:00";
        log.info("历史累计应收未收款统计 : 当前时间==={}", now);
        log.info("历史累计应收未收款统计 : 90天==={}", endTime90);
        log.info("历史累计应收未收款统计 : 180天==={}", endTime180);
        // 查询<90天
        Map<String, String> historyTime90 = new HashMap<String, String>();
        historyTime90.put("endTime", now);
        historyTime90.put("startTime", endTime90);

        // 查询 >=90  <180天
        Map<String, String> historyTime180 = new HashMap<String,String>();
        historyTime180.put("endTime", endTime90);
        historyTime180.put("startTime", endTime180);

        // 查询>=180天
        Map<String, String> historyTime = new HashMap<String,String>();
        historyTime.put("endTime", endTime180);
        historyTime.put("startTime", "");

        // 组装当前登录人对本年签约额的权限
        buildPermissionsForPo(po, EntityHelper.RbHeTong0);

        // 90天
        List<BenNianQianYueEVO> h90List = huikuanjihuaMapper.queryHistoryWeiShouKuan( po, historyTime90.get("startTime"), historyTime90.get("endTime") );
        // 计算
        BigDecimal h90Value = BigDecimal.ZERO;
        if( h90List.size()>0 ){
            for( BenNianQianYueEVO h90:h90List ){
                h90Value = h90Value.add(h90.getValue());
            }
        }

        // 180天
        List<BenNianQianYueEVO> h180List = huikuanjihuaMapper.queryHistoryWeiShouKuan( po, historyTime180.get("startTime"), historyTime180.get("endTime") );
        // 计算
        BigDecimal h180Value = BigDecimal.ZERO;
        if( h180List.size()>0 ){
            for( BenNianQianYueEVO h180:h180List ){
                h180Value = h180Value.add(h180.getValue());
            }
        }

        // 大于180天
        List<BenNianQianYueEVO> hList = huikuanjihuaMapper.queryHistoryWeiShouKuan( po, historyTime.get("startTime"), historyTime.get("endTime") );
        // 计算
        BigDecimal hValue = BigDecimal.ZERO;
        if( hList.size()>0 ){
            for( BenNianQianYueEVO h:hList ){
                hValue = hValue.add(h.getValue());
            }
        }

        // 地域名称作为Y轴data集合
        List<String> yData = new ArrayList<String>();
        List<String> xData = new ArrayList<String>();
        yData.add("<90天");
        xData.add(h90Value.toString());
        yData.add("90天~180天");
        xData.add(h180Value.toString());
        yData.add(">=180天");
        xData.add(hValue.toString());

        // 计算总数
        BigDecimal total = BigDecimal.ZERO;
        total = total.add(h90Value);
        total = total.add(h180Value);
        total = total.add(hValue);

        // 设置Y轴数据
        StatisticsYVO trsyVo = new StatisticsYVO();
        trsyVo.setData( yData );
        trsyVo.setName( "历史累计应收未收款统计" );

        // 设置整个图标XY轴数据
        StatisticsXYVO trsVo = new StatisticsXYVO();
        trsVo.setXAxis(xData);
        trsVo.setYyyAxis(trsyVo);
        trsVo.setTotal(total);
        Integer totalZero = total.compareTo( BigDecimal.ZERO );
        if( totalZero<=0 ){
            Short isShow = 0;
            trsVo.setIsShow(isShow);
        }
        return trsVo;
    }

    /**
     * 季度统计
     * @param monthData
     * @return
     */
    private StatisticsXYVO queryNowYearHuiKuanQuarter( Map<Integer, Map<String, String>> monthData ){
        if( monthData.size()<=0 ) return null;
        // 获取季度信息
        Map<Integer, List<Integer>> quarterArr = getQuarter();

        Map<Integer, String> numberName = new HashMap<Integer, String>();
        numberName.put(1, "一");
        numberName.put(2, "二");
        numberName.put(3, "三");
        numberName.put(4, "四");

        Map<Integer, BigDecimal> planMap = new HashMap<Integer, BigDecimal>();
        Map<Integer, BigDecimal> onTimeMap = new HashMap<Integer, BigDecimal>();
        Map<Integer, BigDecimal> overdueMap = new HashMap<Integer, BigDecimal>();
        // 总和值初始化
        for (int i=1; i<=4; i++ ){
            planMap.put(i, BigDecimal.ZERO);
            onTimeMap.put(i, BigDecimal.ZERO);
            overdueMap.put(i, BigDecimal.ZERO);
        }
        Set<Integer> quarterKeys = quarterArr.keySet();
        for ( int i=1; i<=12; i++ ){
            for( Integer quarterKey:quarterKeys ){
                if( quarterArr.get(quarterKey).contains(i) ){
                    BigDecimal planMonthValue = new BigDecimal(monthData.get(i).get("plan"));
                    BigDecimal onTimeMonthValue = new BigDecimal(monthData.get(i).get("onTime"));
                    BigDecimal overdueMonthValue = new BigDecimal(monthData.get(i).get("overdue"));

                    BigDecimal planValue = planMap.get(quarterKey);
                    planValue = planValue.add(planMonthValue);
                    planMap.put( quarterKey, planValue);

                    BigDecimal onTimeValue = onTimeMap.get(quarterKey);
                    onTimeValue = onTimeValue.add(onTimeMonthValue);
                    onTimeMap.put( quarterKey, onTimeValue);

                    BigDecimal overdueValue = overdueMap.get(quarterKey);
                    overdueValue = overdueValue.add(overdueMonthValue);
                    overdueMap.put( quarterKey, overdueValue);

                }
            }
        }

        List<String> yQuarterData = new ArrayList<String>();
        List<Map<String, BigDecimal>> xQuarterData = new ArrayList<Map<String, BigDecimal>>();
        for (int i=1; i<=4; i++ ){
            yQuarterData.add( "第"+numberName.get(i)+"季度");
            Map<String, BigDecimal> xData = new HashMap<String, BigDecimal>();
            xData.put("plan", planMap.get(i));
            xData.put("onTime", onTimeMap.get(i));
            xData.put("overdue", overdueMap.get(i));
            xQuarterData.add( xData );
        }

        // 设置Y轴数据
        StatisticsYVO trsyVo = new StatisticsYVO();
        trsyVo.setData( yQuarterData );
        trsyVo.setName( "本年回款统计" );
        StatisticsXYVO quarterXY = new StatisticsXYVO();
        quarterXY.setXAxis(xQuarterData);
        quarterXY.setYyyAxis(trsyVo);
        return quarterXY;
    }

    @Override
    public Map<String, StatisticsXYVO> queryNowYearMonthAndQuarter(ChartCommonPermissionsPO po) {
        // 组装当前登录人对本年签约额的权限
        buildPermissionsForPo(po, EntityHelper.RbHeTong0);
        // 获取季度信息
        Map<Integer, List<Integer>> quarterArr = getQuarter();
        Set<Integer> quarterKeys = quarterArr.keySet();

        List<CashTransferSchemesVO> monthList = tRbhetong0Mapper.queryNowYearMonth( po );

        // 地域名称作为Y轴data集合
        List<String> yMonthData = new ArrayList<String>();
        List<String> xMonthData = new ArrayList<String>();
        Map<Integer, BigDecimal> quarterMap = new HashMap<Integer, BigDecimal>();
        // 总和值初始化
        for (int i=1; i<=4; i++ ){
            quarterMap.put(i, BigDecimal.ZERO);
        }

        // ---------------------------------------------------------
        //  月度  Start
        // ----------------------------------------------------------------------------
        for ( int i=1; i<=12; i++ ){
            BigDecimal monthValue = BigDecimal.ZERO;
            for (CashTransferSchemesVO month:monthList) {
                Integer riQi  = month.getRiqi();
                if( riQi==i ){
                    monthValue = month.getJine();
                }
            }
            xMonthData.add(i+"月");
            yMonthData.add(monthValue.toString());

            for( Integer quarterKey:quarterKeys ){
                if( quarterArr.get(quarterKey).contains(i) ){
                    BigDecimal quarterValue = quarterMap.get(quarterKey);
                    quarterValue = quarterValue.add(monthValue);
                    quarterMap.put( quarterKey, quarterValue);
                }
            }
        }
        // ---------------------------------------------------------
        //  月度  End
        // ----------------------------------------------------------------------------

        // 月度 - 设置Y轴数据
        StatisticsYVO monthYVo = new StatisticsYVO();
        monthYVo.setData( yMonthData );
        monthYVo.setName( "本年签约额统计" );
        StatisticsXYVO monthXY = new StatisticsXYVO();
        monthXY.setXAxis(xMonthData);
        monthXY.setYyyAxis(monthYVo);

        // ---------------------------------------------------------
        //  季度  Start
        // ----------------------------------------------------------------------------
        Map<Integer, String> numberName = new HashMap<Integer, String>();
        numberName.put(1, "一");
        numberName.put(2, "二");
        numberName.put(3, "三");
        numberName.put(4, "四");

        List<String> yQuarterData = new ArrayList<String>();
        List<String> xQuarterData = new ArrayList<String>();
        for (int i=1; i<=4; i++ ){
            xQuarterData.add( "第"+numberName.get(i)+"季度");
            yQuarterData.add(quarterMap.get(i).toString());
        }
        // 季度 - 设置Y轴数据
        StatisticsYVO quarterYVo = new StatisticsYVO();
        quarterYVo.setData( yQuarterData );
        quarterYVo.setName( "本年签约额统计" );
        StatisticsXYVO quarterXY = new StatisticsXYVO();
        quarterXY.setXAxis(xQuarterData);
        quarterXY.setYyyAxis(quarterYVo);
        // ---------------------------------------------------------
        //  季度  End
        // ----------------------------------------------------------------------------

        Map<String, StatisticsXYVO> monthAndQuarterData = new HashMap<String, StatisticsXYVO>();
        monthAndQuarterData.put("month", monthXY);
        monthAndQuarterData.put("quarter", quarterXY);

        return monthAndQuarterData;
    }

    /**
     * 获取季度信息
     * @return
     */
    private Map<Integer, List<Integer>> getQuarter(){
        Map<Integer, List<Integer>> quarterArr = new HashMap<Integer, List<Integer>>();
        List<Integer> quarter1 = new ArrayList<Integer>();
        quarter1.add(1);
        quarter1.add(2);
        quarter1.add(3);
        quarterArr.put(1,quarter1);

        List<Integer> quarter2 = new ArrayList<Integer>();
        quarter2.add(4);
        quarter2.add(5);
        quarter2.add(6);
        quarterArr.put(2,quarter2);

        List<Integer> quarter3 = new ArrayList<Integer>();
        quarter3.add(7);
        quarter3.add(8);
        quarter3.add(9);
        quarterArr.put(3,quarter3);

        List<Integer> quarter4 = new ArrayList<Integer>();
        quarter4.add(10);
        quarter4.add(11);
        quarter4.add(12);
        quarterArr.put(4,quarter4);
        return quarterArr;
    }

    /**
     * 商机
     * @param po
     * @return
     */
    private JSONObject shangJiNewAddStatistics( ReportLeadPO po ){
        // 查询权限
        ChartCommonPermissionsPO ccpPo = new ChartCommonPermissionsPO();
        ccpPo.setTenantCode(UserContextHolder.getTenant());
        // 商机权限
        buildPermissionsForPo(ccpPo, EntityHelper.NicheCode);
        po.setHOwningDept( ccpPo.getPOwningDept() );
        po.setPOwningDept( ccpPo.getPOwningDept() );
        po.setTenantCode( ccpPo.getTenantCode() );
        po.setPOwningUser( ccpPo.getPOwningUser() );
        po.setIsNone( ccpPo.getIsNone() );

        // 判断部门是否为空
        String deptId = po.getDeptId();

        if( deptId==null || deptId.length()<=0 ){ // 部门条件为空直接查询商机
            log.info("查询商机新增数量条件 == {}", JSON.toJSON(po));
            WebStatisticsXYVO webVo = nicheCodeService.queryNowYearShangJi( po );
            log.info("查询商机新增数量结果 == {}", JSON.toJSON(webVo));
            JSONObject jsonObject = (JSONObject) JSONObject.toJSON(webVo);
            return jsonObject;
        }else{ // 部门条件存在 , 依据部门统计商机
            // x轴
            List<String> xData = new ArrayList<String>();
            xData.add("本周");
            xData.add("前1周");
            xData.add("前2周");
            xData.add("前3周");
            xData.add("前4周");
            // y轴
            List<String> yData =  new ArrayList<String>();
            yData.add("0.00");
            yData.add("0.00");
            yData.add("0.00");
            yData.add("0.00");
            yData.add("0.00");
            // 组装y轴数据
            StatisticsYVO yVo = new StatisticsYVO();
            yVo.setName("商机新增数量统计");
            yVo.setData( yData );

            WebStatisticsXYVO webVo = new WebStatisticsXYVO();
            webVo.setXAxis( xData );
            webVo.setYyyAxis(yVo);

            JSONObject jsonObject = (JSONObject) JSONObject.toJSON(webVo);
            return jsonObject;
        }
    }

    /**
     * 商机-按行业分布
     * @param po
     * @return
     */
    private JSONObject shangJiNewAddIndustryStatistics( ReportLeadPO po ){
        WebStatisticsXYVO webVo = nicheCodeService.queryNowYearShangJiByIndustry( po );
        log.info("查询商机新增数量=按行业分布 == {}", JSON.toJSON(webVo));
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(webVo);
        return jsonObject;
    }

    /**
     * 超能保-商机-新增查询
     * @param po
     * @return
     */
    private JSONObject shangJiChaoNengBaoNewAddStatistics( ReportLeadPO po ){
        // 查询权限
        ChartCommonPermissionsPO ccpPo = new ChartCommonPermissionsPO();
        ccpPo.setTenantCode(UserContextHolder.getTenant());
        // 商机权限
        buildPermissionsForPo(ccpPo, EntityHelper.RbShangJi1);
        po.setHOwningDept( ccpPo.getPOwningDept() );
        po.setPOwningDept( ccpPo.getPOwningDept() );
        po.setTenantCode( ccpPo.getTenantCode() );
        po.setPOwningUser( ccpPo.getPOwningUser() );
        po.setIsNone( ccpPo.getIsNone() );

        // 判断部门是否为空
        String deptId = po.getDeptId();

        if( deptId==null || deptId.length()<=0 ){ // 部门条件为空直接查询商机
            log.info("查询商机新增数量条件 == {}", JSON.toJSON(po));
            WebStatisticsXYVO webVo = chaoNengBaoShangJiService.queryNowYearChaoNengBaoShangJi( po );
            log.info("查询商机新增数量结果 == {}", JSON.toJSON(webVo));
            JSONObject jsonObject = (JSONObject) JSONObject.toJSON(webVo);
            return jsonObject;
        }else{ // 部门条件存在 , 依据部门统计商机
            // x轴
            List<String> xData = new ArrayList<String>();
            xData.add("本周");
            xData.add("前1周");
            xData.add("前2周");
            xData.add("前3周");
            xData.add("前4周");
            // y轴
            List<String> yData =  new ArrayList<String>();
            yData.add("0.00");
            yData.add("0.00");
            yData.add("0.00");
            yData.add("0.00");
            yData.add("0.00");
            // 组装y轴数据
            StatisticsYVO yVo = new StatisticsYVO();
            yVo.setName("商机新增数量统计");
            yVo.setData( yData );

            WebStatisticsXYVO webVo = new WebStatisticsXYVO();
            webVo.setXAxis( xData );
            webVo.setYyyAxis(yVo);

            JSONObject jsonObject = (JSONObject) JSONObject.toJSON(webVo);
            return jsonObject;
        }
    }
}
